import sys
import os
import datetime
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from models.invoice  import Invoice
from models.company  import Company
from models.state    import State
from models.personal import Personal

class InvoiceService():

	class Index(webapp.RequestHandler):
		def get(self):

			path = os.path.join(os.path.dirname(__file__), '../views/invoices/index.html')
			html = template.render(path, {'invoices' : Invoice.all().order('-created'), 'lastInvoice' : State.lastInvoice() })
			self.response.out.write(html)

	class Create(webapp.RequestHandler):
		def get(self):
			path = os.path.join(os.path.dirname(__file__), '../views/invoices/create.html')
			html = template.render(path, {'companies': Company.all(), 'lastInvoice' : State.lastInvoice()})
			self.response.out.write(html)
		def post(self):
			invoice = Invoice.get_by_number(str(self.request.get('number')))
			if invoice:
				self.response.out.write('the invoice number ' + invoice.number + ' is already in use')
				return
			if not invoice:
				try:
					invoice = Invoice()
					invoice.number      = str(self.request.get('number'))
					invoice.company     = str(self.request.get('company'))
					invoice.comments    = str(self.request.get('comments'))
					invoice.startDate   = datetime.datetime.strptime(self.request.get('startDate'), "%Y-%m-%d")
					invoice.endDate     = datetime.datetime.strptime(self.request.get('endDate'), "%Y-%m-%d")
					invoice.hours       = float(self.request.get('hours'))
					invoice.rate        = float(self.request.get('rate'))
					invoice.taxRate     = float(self.request.get('taxRate'))
					invoice.paid        = str(self.request.get('paid')) == 'true'
					invoice.sent        = str(self.request.get('sent')) == 'true'
					invoice.range       = [invoice.startDate, invoice.endDate]
					invoice.put()

					self.response.out.write('ok')
					return
				except:
					exc_type, exc_value, exc_traceback = sys.exc_info()
					self.response.out.write(exc_value)
					return
				
	class Update(webapp.RequestHandler):
		def get(self, number):
			invoice = Invoice.get_by_number(str(number))
			if invoice:
				path    = os.path.join(os.path.dirname(__file__), '../views/invoices/update.html')
				html    = template.render(path, {'invoice' : invoice, 'companies' : Company.all()})
				self.response.out.write(html)
				return
			self.response.out.write('invoice does not exist')
	
		def post(self, number):
			invoice = Invoice.get_by_number(str(number))
			if not invoice:
				self.response.out.write('the invoice number ' + invoice.number + ' does not exist.')
				return
			if invoice:
				try:
					invoice.company   = str(self.request.get('company'))
					invoice.comments  = str(self.request.get('comments'))
					invoice.startDate = datetime.datetime.strptime(self.request.get('startDate'), "%Y-%m-%d")
					invoice.endDate   = datetime.datetime.strptime(self.request.get('endDate'), "%Y-%m-%d")
					invoice.hours     = float(self.request.get('hours'))
					invoice.rate      = float(self.request.get('rate'))
					invoice.taxRate   = float(self.request.get('taxRate'))
					invoice.paid      = str(self.request.get('paid')) == 'true'
					invoice.sent      = str(self.request.get('sent')) == 'true'
					invoice.range     = [invoice.startDate, invoice.endDate]
					invoice.put()
					self.response.out.write('ok')
					return
				except:
					exc_type, exc_value, exc_traceback = sys.exc_info()
					self.response.out.write(exc_value)
					return
		
	class Delete(webapp.RequestHandler):
		def get(self, number):
			invoice = Invoice.get_by_number(str(number))
			if invoice:
				path = os.path.join(os.path.dirname(__file__), '../views/invoices/delete.html')
				html = template.render(path, {'invoice' : invoice})
				self.response.out.write(html)
			else:
				self.response.out.write('this invoice does not exist')
		def post(self, number):
			invoice = Invoice.get_by_number(str(number))
			if invoice:
				invoice.delete()
				self.response.out.write('ok')
				return
			self.response.out.write('invoice not found or no longer exists')
			
	class Open(webapp.RequestHandler):
		def get(self, number):
			path = os.path.join(os.path.dirname(__file__), '../views/invoices/template.html')
			html = template.render(path, {'invoice' : Invoice.get_by_number(str(number)), 'personal' : Personal.get() })
			self.response.out.write(html)